package com.hzit.security.controller;

import com.hzit.security.entity.User;
import com.hzit.security.mapper.UserMapper;
import com.hzit.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserMapper userMapper;
	//1. 用户登录页面
	@GetMapping("/login")
	public String login(){
		return "login";
	}
	//2. 得到用户列表
	@GetMapping("/list")
	@ResponseBody
	@Secured({"ROLE_user:userlist"})
	// @PreAuthorize("hasAuthority('user:userlist')")      //有权限user:userlist就可以访问此资源
	// @PreAuthorize("hasAnyAuthority('user:userlistxxxx','student:update')")  // 有其中一个权限就可以访问
	// @PreAuthorize("hasRole('role:rolelist.action')")    // 有角色role:rolelist.action可以访问此资源
	public R list(){
		List<User> users = userMapper.selectAll();
		return R.ok(users);
	}
	//3. 对输出数据进行筛选
	@GetMapping("/list2")
	@ResponseBody
	// @PreAuthorize("hasAuthority('user:userlist')")       // 前置授权,方法未执行前
	@PostAuthorize("hasAuthority('user:userlistxxx')")      // 后置授权,方法执行后判断
	// @PostFilter("filterObject.username == 'test1'")         // 对方法的返回结果进行过滤,其中 filterObject代表返回的集合中的某个对象
	public List<User> list2(){
		User user1 = new User("aaa", "test1", "123");
		User user2 = new User("bbb", "test2", "456");
		List<User> users = new ArrayList<>();
		users.add(user1);
		users.add(user2);
		System.out.println("users = " + users);
		return users;
	}
	//4.  对传入的参数进行过滤
	@GetMapping("/list3")
	@ResponseBody
	@PreFilter("filterObject.username == 'test2'")
	public List<User> list3(@RequestBody List<User> users){
		return users;
	}
}
